/**
 * @file dbgenre.c
 * @brief Fichier source du module dbgenre.
 *
 * @author Rachid Delory, Mamadou Keita, Florian Bernard
 */

/* *********************************************************************

                       Librairies de database

********************************************************************* */

#include "dbgenre.h"

/* *********************************************************************

                        Fonctions

********************************************************************* */

void recuperation_DGen(Ensemble * element, const int id, DBTYPE type)
{
  if(element)
    {
      DataBase data;
      ouvrir_Db();
      if(type == OEUVRE_DGEN)
	{
	  prepare_Db(&data, "select rowid, libelle from genre where rowid in (select id_genre from oeuvreGenre where id_oeuvre =  ?)");
	  bindValueInt_Db(&data, 1, id);
	}
      else if(type == REGROUPEMENT_DGEN)
	{
	  prepare_Db(&data, "select rowid, libelle from genre where rowid in (select id_genre from regroupementGenre where id_regroupement = ?)");
	  bindValueInt_Db(&data, 1, id);
	}
      else if(type == GENRE_DGEN)
	{
	  prepare_Db(&data, "select rowid, libelle from genre");
	}
      else if(type == SEUL_DGEN)
	{
	  prepare_Db(&data, "select rowid, libelle from genre where rowid = ?");
	  bindValueInt_Db(&data, 1, id);
	}
      while(execute_Db(&data))
	{
	  Genre gen;
	  init_Gen(&gen);
	  setId_Gen(&gen, getValueInt_Db(&data,0));
	  setLibelle_Gen(&gen, getValueText_Db(&data,1));

	  insert_Ens(element, &gen, creer_Gen, copier_Gen);

	  liberer_Gen(&(gen));
	}
      finalise_Db(&data);
    }
}
void insertion_DGen(Genre *genre)
{
  if(genre)
    {
      DataBase data;
      ouvrir_Db();
      if(getSup_Gen(genre) == 1)
	{
	  suppression_DGen(getId_Gen(genre));
	  return;
	}
      if(getId_Gen(genre) == 0)
	{
	  prepare_Db(&data, "insert into genre (libelle) values (?)");
	}
      else
	{
	  if(getMaj_Gen(genre) == 1)
	    {
	      prepare_Db(&data, "update genre set libelle = ? where rowid = ?");
	      bindValueInt_Db(&data, 2, getId_Gen(genre));
	    }
	}
      if(getMaj_Gen(genre) == 1 || getId_Gen(genre) == 0)
	{
	  bindValueText_Db(&data, 1, getLibelle_Gen(genre));
	  if(execute_Db(&data))
	    {
	      
	    }
	  finalise_Db(&data);
	}
      if(getId_Gen(genre) == 0)
	{
	  prepare_Db(&data, "select max(rowid) from genre");
	  if(execute_Db(&data))
	    {
	      setId_Gen(genre, getValueInt_Db(&data, 0));
	    }
	  finalise_Db(&data);
	}
    }
}

void suppression_DGen(const int id)
{
  if(id > 0)
    {
      DataBase data;
      ouvrir_Db();
      prepare_Db(&data, "delete from Genre where rowid = ?");
      bindValueInt_Db(&data, 1, id);
      if (execute_Db(&data))
	{

	}
      finalise_Db(&data);
      prepare_Db(&data, "delete from RegroupementGenre where id_genre = ?");
      bindValueInt_Db(&data, 1, id);
      if (execute_Db(&data))
	{

	}
      finalise_Db(&data);
    }
}

void regression_DGen()
{

}
